﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.Net;
using System.Threading;
using System.Xml.Linq;
using System.Xml.Serialization;
using System.Xml;
using System.IO;
using System.Windows.Forms;

namespace gui
{
    /// <summary>
    /// Класс клиента, работающего на сокетах
    /// </summary>
    class SocketClient
    {
        /// <summary>
        /// Адрес сервера
        /// </summary>
        private IPAddress _host;

        /// <summary>
        /// Порт
        /// </summary>
        private int _port;

        /// <summary>
        ///  Логин пользователя
        /// </summary>
        private string _login;

        /// <summary>
        /// Сокет клиента
        /// </summary>
        private Socket _client;

        /// <summary>
        /// Настройки клиента
        /// </summary>
        private ClientSettings _settings;

        Config config = new Config();

        /// <summary>
        /// Инициализация клиента
        /// </summary>
        public SocketClient()
        {
            
        }

        /// <summary>
        /// Подключение клиента к серверу
        /// </summary>
        public void SocketConnect()
        {
            try
            {
                
                this._settings = new ClientSettings();
                config.GetConfig();
                this._host = IPAddress.Parse(config.Ip);
                this._port = config.Port;
                this._login = config.Login;
                this._client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                this._client.Connect(this._host, this._port);
            }
            catch (SocketException error)
            {
                MessageBox.Show(error.Message, "Ошибка");
            }
        }

        /// <summary>
        /// Отключение клиента от сервера
        /// </summary>
        public void closeConnect() 
        {
            try
            {
                if (_client.Connected)
                {
                    this._client.Shutdown(SocketShutdown.Both);
                    this._client.Close();
                }
            }
            catch (ObjectDisposedException exp)
            {
                MessageBox.Show(exp.Message, "Ошибка");
            }
            
        }

        /// <summary>
        /// Состояние клиента
        /// </summary>
        /// <returns>Возвращает true если клиент подключен к серверу, иначе false.</returns>
        public bool State()
        {
            bool state = false;
            if (this._client.Connected)
            {
                state = true;
            }
            return state;
        }

        /// <summary>
        /// Получение входящих сообщений
        /// </summary>
        public string Receive()
        {
            string message = String.Empty;
            try
            {
                if (this._client.Available == 0)
                {
                    return message;
                }

                byte[] inputText = new byte[this._client.Available];
                this._client.Receive(inputText);
                if (inputText.Length != 0)
                {
                    XElement element = XElement.Parse(Encoding.UTF8.GetString(inputText));
                    string date = element.Element(this._settings.MessageDateElement).Value;
                    string text = element.Element(this._settings.MessageTextElement).Value;
                    string login = element.Element(this._settings.MessageLoginElement).Value;

                    DataBase db = new DataBase();

                    // Соединяемся с базой
                    db.OpenConnection();

                    //Добавляем запись в базу
                    db.CreatData(text, DateTime.Now);

                    message = login + " (" + date + ")\n" + text + "\n";
                }

            }
            catch
            {

            }
            return message;
        }

        /// <summary>
        /// Отправка сообщения
        /// </summary>
        /// <param name="message">Текст сообщения</param>
        public void Send(string message)
        {
            try
            {
                DateTime dateTime = DateTime.Now;
                string[] stringArrayDateTime = dateTime.ToString().Split(' ');
                string date = stringArrayDateTime[0];
                string time = stringArrayDateTime[1].Split('.')[0];
                XElement xml = new XElement(this._settings.MainElementMessage,
                                    new XElement(this._settings.MessageDateElement, date + " " + time),
                                    new XElement(this._settings.MessageLoginElement, this._login),
                                    new XElement(this._settings.MessageTextElement, message));
                byte[] messageForByte = Encoding.UTF8.GetBytes(xml.ToString());
                this._client.Send(messageForByte);
            }
            catch (SocketException error)
            {
                MessageBox.Show(error.Message, "Ошибка");
            }
        }

        public string GetLogin()
        {
            return this._login;
        }
       
    }
}
